package com.huikeportal.controller;

import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.huikeportal.controller.common.MessageManager;
import com.huikeportal.model.Article;
import com.huikeportal.model.Feedback;
import com.huikeportal.model.UserInfo;
import com.huikeportal.service.ArticleService;
import com.huikeportal.service.FeedbackService;
import com.huikeportal.service.LoginService;

@Controller
@Scope("prototype")
public class IndexController {

	@Autowired
	private HttpSession session;

	@Autowired
	private FeedbackService feedbackService;

	@Autowired
	private ArticleService articleService;

	@Autowired
	private HttpServletRequest req;
	
	@Autowired
	private LoginService loginService;

	@InitBinder("feedback")
	public void initBinder(WebDataBinder binder) {
		binder.setFieldDefaultPrefix("feedback.");
	}

	@RequestMapping("/index")
	public String index(ModelMap model) throws Exception {
		if (!"".equals(session.getAttribute("userName"))
				&& session.getAttribute("userName") != null) {
			model.addAttribute("userName", session.getAttribute("realName")
					.toString());
		}
		if (req.getAttribute("usPsd") != null
				&& !"".equals(req.getAttribute("usPsd"))) {
			model.addAttribute("usPsd", req.getAttribute("usPsd"));
		}
		// if (!"".equals(req.getAttribute("errorMsg"))) {
		// model.addAttribute("errorMsg", req.getAttribute("errorMsg")
		// .toString());
		// model.addAttribute("usName", req.getAttribute("usName"));
		// }
		return MessageManager.getMsg("mainPage");

	}
	
	@RequestMapping("/index_mobile")
	public String index_mobile(ModelMap model) throws Exception {
		if (!"".equals(session.getAttribute("userName"))
				&& session.getAttribute("userName") != null) {
			model.addAttribute("userName", session.getAttribute("realName")
					.toString());
		}
		// if (!"".equals(req.getAttribute("errorMsg"))) {
		// model.addAttribute("errorMsg", req.getAttribute("errorMsg")
		// .toString());
		// model.addAttribute("usName", req.getAttribute("usName"));
		// }
		return "index_mobile";
	}
	@RequestMapping("/mobile_login")
	public String mobile_login(ModelMap model) throws Exception {
		if (!"".equals(session.getAttribute("userName"))
				&& session.getAttribute("userName") != null) {
			model.addAttribute("userName", session.getAttribute("realName")
					.toString());
		}
		// if (!"".equals(req.getAttribute("errorMsg"))) {
		// model.addAttribute("errorMsg", req.getAttribute("errorMsg")
		// .toString());
		// model.addAttribute("usName", req.getAttribute("usName"));
		// }
		String gotopage=MessageManager.getMsg("mobileReportUrl");
		model.addAttribute("gotopage", gotopage);
		return "login_mobile";
	}
	@ResponseBody
	@RequestMapping("/getUserId")
	public Map<String, Object> getUserId()throws Exception{
		Map<String, Object> map = new HashMap<String, Object>();
		UserInfo userInfo = (UserInfo) session.getAttribute("sessionUserName");
		userInfo=loginService.getUserInfo(userInfo);
		String userId=userInfo.getUserId();
		map.put("userid", userId);
		return map;
	}
	
	@RequestMapping("/about")
	public String about(ModelMap model) throws Exception {
		if (!"".equals(session.getAttribute("userName"))
				&& session.getAttribute("userName") != null) {
			model.addAttribute("userName", session.getAttribute("realName")
					.toString());
		}
		// if (!"".equals(req.getAttribute("errorMsg"))) {
		// model.addAttribute("errorMsg", req.getAttribute("errorMsg")
		// .toString());
		// model.addAttribute("usName", req.getAttribute("usName"));
		// }
		return "about";

	}
	
	@RequestMapping("/news_mobile")
	public String news_mobile(ModelMap model) throws Exception {
		if (!"".equals(session.getAttribute("userName"))
				&& session.getAttribute("userName") != null) {
			model.addAttribute("userName", session.getAttribute("realName")
					.toString());
		}
		// if (!"".equals(req.getAttribute("errorMsg"))) {
		// model.addAttribute("errorMsg", req.getAttribute("errorMsg")
		// .toString());
		// model.addAttribute("usName", req.getAttribute("usName"));
		// }
		return "news_mobile";

	}
	@RequestMapping("/news")
	public String news(ModelMap model) throws Exception {
		if (!"".equals(session.getAttribute("userName"))
				&& session.getAttribute("userName") != null) {
			model.addAttribute("userName", session.getAttribute("realName")
					.toString());
		}
		// if (!"".equals(req.getAttribute("errorMsg"))) {
		// model.addAttribute("errorMsg", req.getAttribute("errorMsg")
		// .toString());
		// model.addAttribute("usName", req.getAttribute("usName"));
		// }
		Article article = new Article();
		String source = MessageManager.getMsg("articleSource");
		article.setSource(source);
		article.setIndex(1);
		Article article1 = articleService.getFirstArticle(article);
		if (article1 != null) {
			model.addAttribute("img", MessageManager.getMsg("articlePath")
					+ "/" + article1.getPic());
			model.addAttribute("fid", article1.getItem_id());
			model.addAttribute("ftitle", article1.getItem_title());
			List<Article> articleList = articleService.getArticleList(article);
			if (articleList != null) {
				int size = articleList.size();
				if (articleList.size() > 7) {
					model.addAttribute("more", "1");
					size = 7;
				}
				String div = "";

				for (int i = 0; i < size; i++) {
					Article art = articleList.get(i);
					art.setItem_desc(HtmlFormat(art.getItem_desc()));
					div += "<div id=\"toparticle"
							+ art.getItem_id()
							+ "\" class=\"articlelist newsdiv\"><div class=\"em20\"></div><div class=\"articlejianjie\"><div class=\"articleimg\"><img src=\""
							+ MessageManager.getMsg("articlePath")
							+ "/"
							+ art.getPic()
							+ "\" onclick=\"window.open('news_detail?id="
							+ art.getItem_id()
							+ "')\" style=\"width:100%;height:100%\"/></div><div class=\"articlejg\"></div><div class=\"articlexq\"><div class=\"em25  widthall lineh25 font20 click\" onclick=\"window.open('news_detail?id="
							+ art.getItem_id()
							+ "')\">"
							+ art.getItem_title()
							+ "</div><div class=\"em5 widthall\"></div><div class=\"em25 widthall\"></div><div class=\"em20 widthall\"></div><div class=\"em30 gray  widthall lineh30\">"
							+ art.getItem_desc()
							+ "<a class=\"newsdetail\" href=\"news_detail?id="
							+ art.getItem_id()
							+ "\" target=\"_blank\">[详情]</a></div><div class=\"em5 widthall\"></div><div class=\"em30 gray  widthall lineh30\">"
							+ art.getDate()
							+ "</div><div style=\"clear:both\"></div></div></div></div><div class=\"jiange\" style=\"width:100%\"></div>";
				}
				model.addAttribute("divlist", div);
			}
		}
		List<Article> hotlist = articleService.getHotArticles(source);
		Article qianyan = articleService.getQYAtricle(source);
		List<Article> hangye = articleService.getAtricles(1, source);
		List<Article> fangan = articleService.getAtricles(3, source);
		for (int i = 0; i < hotlist.size(); i++) {
			String title = hotlist.get(i).getItem_title();
			int len = title.length();
			if (len > 15) {
				title = title.substring(0, 12) + "...";
				hotlist.get(i).setItem_title(title);
			}
		}
		for (int i = 0; i < hangye.size(); i++) {
			String title = hangye.get(i).getItem_title();
			int len = title.length();
			if (len > 15) {
				title = title.substring(0, 12) + "...";
				hangye.get(i).setItem_title(title);
			}
			hangye.get(i)
					.setItem_desc(HtmlFormat(hangye.get(i).getItem_desc()));
		}
		for (int i = 0; i < fangan.size(); i++) {
			String title = fangan.get(i).getItem_title();
			int len = title.length();
			if (len > 15) {
				title = title.substring(0, 12) + "...";
				fangan.get(i).setItem_title(title);
			}
			fangan.get(i)
					.setItem_desc(HtmlFormat(fangan.get(i).getItem_desc()));
		}
		if (qianyan != null) {
			String title = qianyan.getItem_title();
			int len = title.length();
			if (len > 20) {
				title = title.substring(0, 17) + "...";
				qianyan.setItem_title(title);
			}
			qianyan.setPic(MessageManager.getMsg("articlePath") + "/"
					+ qianyan.getPic());
		}
		model.addAttribute("qianyan", qianyan);
		model.addAttribute("hangye", hangye);
		model.addAttribute("fangan", fangan);
		model.addAttribute("hotlist", hotlist);
		model.addAttribute("index", "1");

		return "news";
	}
	@RequestMapping("/newsxwrd")
	@ResponseBody
	public Map<String, Object> newsxwrd(String index,int isFirst) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		Article article = new Article();
		String source = MessageManager.getMsg("articleSource");
		article.setSource(source);
		article.setIndex(Integer.parseInt(index)*3-2);
		if(isFirst==1){
			Article article1 = articleService.getFirstArticle(article);
			map.put("news",article1);
		}else{
			List<Article> articleList = articleService.getArticleListMobile(article);
			if(articleList.size()>3){
				map.put("more", 1);
			}else{
				map.put("more", 0);
			}
			for (int i = 0; i < articleList.size(); i++) {
				Article art = articleList.get(i);
				art.setItem_desc(HtmlFormat(art.getItem_desc()));
				if(art.getItem_title().length()>15){
					art.setItem_title(art.getItem_title().substring(0, 14)+"...");
				}
			}
			map.put("news",articleList);
		}
		map.put("imgpath", MessageManager.getMsg("articlePath"));
		return map;
	}
	@RequestMapping("/newsjsqy")
	@ResponseBody
	public Map<String, Object> newsjsqy(String index) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		Article article = new Article();
		String source = MessageManager.getMsg("articleSource");
		article.setSource(source);
		article.setIndex(Integer.parseInt(index)*3-3);
		article.setCategory("2");
		List<Article> articleList = articleService.getAtricles2(article);
		if(articleList.size()>3){
			map.put("more", 1);
		}else{
			map.put("more", 0);
		}
		for (int i = 0; i < articleList.size(); i++) {
			Article art = articleList.get(i);
			art.setItem_desc(HtmlFormat(art.getItem_desc()));
			if(art.getItem_title().length()>15){
				art.setItem_title(art.getItem_title().substring(0, 14)+"...");
			}
		}
		map.put("news",articleList);
		map.put("imgpath", MessageManager.getMsg("articlePath"));
		return map;
	}
	@RequestMapping("/newshyyy")
	@ResponseBody
	public Map<String, Object> newshyyy(String index) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		Article article = new Article();
		String source = MessageManager.getMsg("articleSource");
		article.setSource(source);
		article.setIndex(Integer.parseInt(index)*3-3);
		article.setCategory("1");
		List<Article> articleList = articleService.getAtricles2(article);
		if(articleList.size()>3){
			map.put("more", 1);
		}else{
			map.put("more", 0);
		}
		for (int i = 0; i < articleList.size(); i++) {
			Article art = articleList.get(i);
			art.setItem_desc(HtmlFormat(art.getItem_desc()));
			if(art.getItem_title().length()>15){
				art.setItem_title(art.getItem_title().substring(0, 14)+"...");
			}
		}
		map.put("news",articleList);
		map.put("imgpath", MessageManager.getMsg("articlePath"));
		return map;
	}
	@RequestMapping("/newsfajs")
	@ResponseBody
	public Map<String, Object> newsfajs(String index) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		Article article = new Article();
		String source = MessageManager.getMsg("articleSource");
		article.setSource(source);
		article.setIndex(Integer.parseInt(index)*3-3);
		article.setCategory("3");
		List<Article> articleList = articleService.getAtricles2(article);
		if(articleList.size()>3){
			map.put("more", 1);
		}else{
			map.put("more", 0);
		}
		for (int i = 0; i < articleList.size(); i++) {
			Article art = articleList.get(i);
			art.setItem_desc(HtmlFormat(art.getItem_desc()));
			if(art.getItem_title().length()>15){
				art.setItem_title(art.getItem_title().substring(0, 14)+"...");
			}
		}
		map.put("news",articleList);
		map.put("imgpath", MessageManager.getMsg("articlePath"));
		return map;
	}
	@RequestMapping("/news_detail_mobile")
	public String news_detail_mobile(String id,ModelMap model)throws Exception{
		String source = MessageManager.getMsg("articleSource");
		if (id == null) {
			model.addAttribute("exists", "0");
		} else {
			Article article = new Article();
			article.setSource(source);
			article.setItem_id(Integer.parseInt(id));
			Article art = articleService.getArticle(article);
			if (art != null) {
				art.setSource(source);
				Article artp = articleService.getPreArticle(art);
				if (artp != null) {
					model.addAttribute("previousId", artp.getItem_id());
					model.addAttribute("previousNews", artp.getItem_title());
				}
				Article artN = articleService.getNextArticle(art);
				if (artN != null) {
					model.addAttribute("nextId", artN.getItem_id());
					model.addAttribute("nextNews", artN.getItem_title());
				}
				art.setDate(articleService.getTimeAgo(art.getDate()));
				articleService.clickPlusOne(art);
				model.addAttribute("article", art);
				model.addAttribute("exists", "1");
				model.addAttribute("id", id);
				model.addAttribute("articlePath", MessageManager
						.getMsg("articlePath"));
			} else {
				model.addAttribute("exists", "0");
			}
		}
		return "news_detail_mobile";
	}
	@RequestMapping("/newsmore")
	@ResponseBody
	public Map<String, Object> newsmore(String index) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		String str = "0";
		Article article = new Article();
		String source = MessageManager.getMsg("articleSource");
		article.setSource(source);
		article.setIndex(Integer.parseInt(index) * 8);
		List<Article> articleList = articleService.getArticleList(article);
		if (articleList != null) {
			if (articleList.size() > 7) {
				str = "1";
			}
			for (int i = 0; i < articleList.size(); i++) {
				Article art = articleList.get(i);
				String desc = HtmlFormat(art.getItem_desc());
				art.setItem_desc(desc);
			}
		}
		map.put("more", str);
		map.put("articleList", articleList);
		map.put("atriclePath", MessageManager.getMsg("articlePath"));
		return map;
	}

	@RequestMapping("/news_detail")
	public String news_detail(ModelMap model, String id) throws Exception {
		if (!"".equals(session.getAttribute("userName"))
				&& session.getAttribute("userName") != null) {
			model.addAttribute("userName", session.getAttribute("realName")
					.toString());
		}
		// if (!"".equals(req.getAttribute("errorMsg"))) {
		// model.addAttribute("errorMsg", req.getAttribute("errorMsg")
		// .toString());
		// model.addAttribute("usName", req.getAttribute("usName"));
		// }
		String source = MessageManager.getMsg("articleSource");
		if (id == null) {
			model.addAttribute("exists", "0");
		} else {
			Article article = new Article();
			article.setSource(source);
			article.setItem_id(Integer.parseInt(id));
			Article art = articleService.getArticle(article);
			if (art != null) {
				art.setSource(source);
				Article artp = articleService.getPreArticle(art);
				if (artp != null) {
					model.addAttribute("previousId", artp.getItem_id());
					model.addAttribute("previousNews", artp.getItem_title());
				}
				Article artN = articleService.getNextArticle(art);
				if (artN != null) {
					model.addAttribute("nextId", artN.getItem_id());
					model.addAttribute("nextNews", artN.getItem_title());
				}
				art.setDate(articleService.getTimeAgo(art.getDate()));
				articleService.clickPlusOne(art);
				model.addAttribute("article", art);
				model.addAttribute("exists", "1");
				model.addAttribute("id", id);
				model.addAttribute("articlePath", MessageManager
						.getMsg("articlePath"));
			} else {
				model.addAttribute("exists", "0");
			}
		}
		List<Article> hotlist = articleService.getHotArticles(source);
		if (hotlist != null) {
			for (int i = 0; i < hotlist.size(); i++) {
				String title = hotlist.get(i).getItem_title();
				int len = title.length();
				if (len > 15) {
					title = title.substring(0, 12) + "...";
					hotlist.get(i).setItem_title(title);
				}
			}
			model.addAttribute("hotlist", hotlist);
		}
		return "news_detail";
	}

	@RequestMapping("/news_1")
	public String news_1(ModelMap model) throws Exception {
		if (!"".equals(session.getAttribute("userName"))
				&& session.getAttribute("userName") != null) {
			model.addAttribute("userName", session.getAttribute("realName")
					.toString());
		}
		return "news_1";

	}

	@RequestMapping("/news_2")
	public String news_2(ModelMap model) throws Exception {
		if (!"".equals(session.getAttribute("userName"))
				&& session.getAttribute("userName") != null) {
			model.addAttribute("userName", session.getAttribute("realName")
					.toString());
		}
		return "news_2";

	}

	@RequestMapping("/news_3")
	public String news_3(ModelMap model) throws Exception {
		if (!"".equals(session.getAttribute("userName"))
				&& session.getAttribute("userName") != null) {
			model.addAttribute("userName", session.getAttribute("realName")
					.toString());
		}
		return "news_3";

	}
	
	@RequestMapping("/about_mobile")
	public String about_mobile(ModelMap model) throws Exception {
		
		return "about_mobile";

	}
	
	@RequestMapping("/commitFeedback")
	@ResponseBody
	public String commitFeedback(ModelMap model, Feedback feedback)
			throws Exception {
		feedback.setName(URLDecoder.decode(feedback.getName(), "UTF-8"));
		feedback.setQuestion(URLDecoder.decode(feedback.getQuestion(), "UTF-8"));
		feedbackService.insertFeedback(feedback);
		return "1";
	}

	private String HtmlFormat(String html) {
		html = html.replaceAll(" ", "").replaceAll("　", "")
				.replaceAll("\t", "").replaceAll("\n", "").replaceAll("\r", "");
		Pattern pattern = Pattern.compile("<.+?>", Pattern.DOTALL);
		Matcher matcher = pattern.matcher(html);
		html = matcher.replaceAll("").replaceAll(" ", "").replaceAll("&nbsp;",
				"").replaceAll("　", "");
		int len = 20;
		if (html.length() < len) {
			len = html.length();
		}
		return html.substring(0, len);
	}
}
